package com.cw.lang.common.framework.rpc;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import com.cw.base.common.model.enums.EnumRpcExceptionConfig;
import com.cw.lang.common.constants.HttpStatusConstant;
import com.cw.lang.common.enums.EnumResponseType;
import com.cw.lang.common.exception.AbstractExceptionWrapper;
import com.cw.lang.common.exception.BizException;
import com.cw.lang.common.exception.CheckException;
import com.cw.lang.common.exception.SystemException;
import com.cw.lang.common.framework.aop.annotation.IntegrationHandler;
import com.cw.lang.common.framework.enums.EnumRpcError;
import com.cw.lang.common.framework.utils.CommonResponseUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author chenw
 * @version $$Id: ExceptionCatchIntegrationHandlerAspect.java, v 0.1 2018/10/31 4:24 PM chenw Exp $$
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 1000)
@Aspect
@Slf4j
public class ExceptionCatchIntegrationHandlerAspect {

    /**
     * aop处理
     *
     * @param jp jp
     * @return Object
     * @throws Throwable Throwable
     */
    @Around(value = "@annotation(integrationHandler)")
    public Object aroundMethod(final ProceedingJoinPoint jp, IntegrationHandler integrationHandler) throws Throwable {
        try {
            Object result = jp.proceed();
            if (integrationHandler.isRpcExceptionThrowEnabled() == EnumRpcExceptionConfig.FALSE) {
                return result;
            }
            // 如果返回信息中没有rpcResponseType，则说明没有进行rpc调用，所以也进行直接返回
            if (CommonResponseUtil.getRpcResponseType() == null || EnumResponseType.SUCCESS.equals(
                CommonResponseUtil.getRpcResponseType())) {
                return result;
            } else if (EnumResponseType.VALIDATE_ERR.equals(CommonResponseUtil.getRpcResponseType())) {
                throw new CheckException(CommonResponseUtil.getRpcErrorCode(),
                    CommonResponseUtil.getRpcErrorMessage());
            } else {
                log.error("系统调用出现异常, code: [{}], message: [{}]", CommonResponseUtil.getRpcErrorCode(),
                    CommonResponseUtil.getRpcErrorMessage());
                throw new BizException(CommonResponseUtil.getRpcErrorCode(),
                    CommonResponseUtil.getRpcErrorMessage());
            }
        } catch (AbstractExceptionWrapper e) {
            // 如果是系统内部的异常，直接向上抛，无需处理
            throw e;
        } catch (Exception e) {
            log.error("未知异常：message: [{" + e.getMessage() + "}]", e);
            throw new SystemException(HttpStatusConstant.OK, EnumRpcError.SYSTEM_ERROR.getCode(), e.getMessage());
        } finally {
            CommonResponseUtil.removeCommonResponseRpcInfo();
        }
    }
}
